package javase.javase02.thread;

/**
 * @author: Gan
 * @date 2021/4/22 0022 17:01  标识
 * @description: **2.启动3个线程打印递增的数字**
 * 线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10,
 * 然后是线程3打印11,12,13,14,15. 接着再由线程1打印16,17,18,19,20....以此类推, 直到打印到75
 **/
public class Day21Work02 {
    public static void main(String[] args) {
        NumPrint np = new NumPrint();

        Thread t1 = new Thread(() -> {
            while (np.num <= 65) {
                try {
                    np.t1();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        });

        Thread t2 = new Thread(() -> {
            while (np.num <= 70) {
                try {
                    np.t2();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread t3 = new Thread(() -> {
            while (np.num <= 75) {
                try {
                    np.t3();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.setName("线程一");
        t2.setName("线程二");
        t3.setName("线程三");
        t1.start();
        t2.start();
        t3.start();
    }
}

class NumPrint {
    public int num = 1;
    public int logo = 1;

    public synchronized void t1() throws InterruptedException {
        //阻塞其他2个进程
        while (logo != 1)
            wait();
        print();
        logo = 2;
        notifyAll();
    }

    public synchronized void t2() throws InterruptedException {
        while (logo != 2)
            wait();
        print();
        logo = 3;
        notifyAll();
    }

    public synchronized void t3() throws InterruptedException {
        while (logo != 3)
            wait();
        print();
        logo = 1;
        notifyAll();
    }

    public void print() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + (num++));
        }
    }
}